<?php
//decode by QQ:270656184 http://www.yunlu99.com/
defined('IN_IA') or exit('Access Denied');

class Bsht_tbkModuleReceiver extends WeModuleReceiver
{
	private function emoji($str)
	{
		$str = json_encode($str);
		$str = preg_replace("#(\\\ud[0-9a-f]{3})#ie", "", $str);
		$str = preg_replace("#(\\\u2[0-9a-f]{3})#ie", "", $str);
		$str = preg_replace("#(\\\u0[0-9a-f]{3})#ie", "", $str);
		$str = json_decode($str);
		$str = trim(str_replace(array(' ', "'", ',', '。', '•', '.', '+', ')', '(', '_', '、', '，', '"'), '', $str));
		return $str;
	}

	function formot_content($content = '', $fansusr)
	{
		global $_W;
		if (empty($content)) {
			return $content;
		}
		load()->model('mc');
		$fansuser = mc_fetch($this->message['from']);
		$replace = array('a' => Array('replace' => '#昵称#', 'name' => 'nickname'), 'b' => Array('replace' => '#积分#', 'name' => 'credit1'), 'c' => Array('replace' => '#余额#', 'name' => 'credit2'), 'd' => Array('replace' => '#国家#', 'name' => 'nationality'), 'e' => Array('replace' => '#省#', 'name' => 'resideprovince'), 'f' => Array('replace' => '#市#', 'name' => 'residecity'));
		foreach ($replace as $rep) {
			$content = str_replace($rep['replace'], $fansuser[$rep['name']], $content);
		}
		return $content;
	}

	private function uid2openid($uid)
	{
		$thisuid = pdo_fetchcolumn('select openid from ' . tablename('mc_mapping_fans') . " where uid='{$uid}'");
		return $thisuid;
	}

	public function sendText($openid, $text)
	{
		$post = '{"touser":"' . $openid . '","msgtype":"text","text":{"content":"' . $text . '"}}';
		$result = $this->sendRes($this->getAccessToken(), $post);
		return $result;
	}

	public function sendNews($news, $openid)
	{
		$result = '{"touser":"' . $openid . '","msgtype":"news","news":{"articles":[{"title":"' . $news['title'] . '","description":"' . $news['description'] . '","url":"' . $news['url'] . '","picurl":"' . $news['picurl'] . '"}]}}';
		$access_token = $this->getAccessToken();
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}";
		$rets = ihttp_request($url, $result);
		return $rets;
	}

	private function sendRes($access_token, $data)
	{
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}";
		load()->func('communication');
		$ret = ihttp_request($url, $data);
		$content = @json_decode($ret['content'], true);
		return $content['errcode'];
	}

	private function getAccessToken()
	{
		global $_W;
		load()->model('account');
		$acid = $_W['acid'];
		if (empty($acid)) {
			$acid = $_W['uniacid'];
		}
		$account = WeAccount::create($acid);
		$token = $account->getAccessToken();
		return $token;
	}

	public function receive()
	{
		global $_W, $_GPC;
		load()->func('logging');
		$settings = $this->module["config"];
		load()->model('mc');
		$mc_infos = mc_fetch($this->message['from']);
		$openid = $this->message['from'];
		$uid = mc_openid2uid($openid);
		if ($this->message['event'] == "subscribe") {
			if (empty($mc_infos['nickname']) || empty($mc_infos['avatar']) || empty($mc_infos['province'])) {
				$openid = $this->message['from'];
				$ACCESS_TOKEN = $this->getAccessToken();
				$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$ACCESS_TOKEN}&openid={$openid}&lang=zh_CN";
				load()->func('communication');
				$json = ihttp_get($url);
				$userInfo = @json_decode($json['content'], true);
				$userInfo['nickname'] = $this->emoji($userInfo['nickname']);
				$mc_infos['nickname'] = $userInfo['nickname'];
				$mc_infos['avatar'] = $userInfo['headimgurl'];
				$mc_infos['province'] = $userInfo['province'];
				$mc_infos['city'] = $userInfo['city'];
				$mc_infos['country'] = $userInfo['country'];
				mc_update($uid, array('nickname' => $userInfo['nickname']));
			}
			pdo_update('bsht_tbk_user', array('follow' => 1), array('uid' => $mc_infos['uid'], 'uniacid' => $mc_infos['uniacid']));
			$fansusr = mc_fetch($this->message['from']);
			if ($fansusr['gender'] == 1) {
				$fansusr['gender'] = '帅哥';
			} elseif ($fansusr['gender'] == 2) {
				$fansusr['gender'] = '美女';
			} elseif (empty($fansusr['gender']) || $fansusr['gender'] == 0) {
				$fansusr['gender'] = '未知';
			}
			$fanssum = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename('bsht_tbk_user') . " WHERE uniacid = :uniacid and follow=1 ", array(':uniacid' => $fansusr['uniacid']));
			$account_name = $_W['account']['name'];
			$fansallnum = $settings["bsht_tbk_fansnum"] + $fanssum;
			if (!empty($settings['bsht_tbk_diyurl1'])) {
				$bsht_tbk_diyurl1 = "<a href='" . $settings['bsht_tbk_diyurl1'] . "'>点击这里</a>";
			}
			if (!empty($settings['bsht_tbk_diyurl2'])) {
				$bsht_tbk_diyurl2 = "<a href='" . $settings['bsht_tbk_diyurl2'] . "'>点击这里</a>";
			}
			if (!empty($settings['bsht_tbk_diyurl3'])) {
				$bsht_tbk_diyurl3 = "<a href='" . $settings['bsht_tbk_diyurl3'] . "'>点击这里</a>";
			}
			$message = htmlspecialchars_decode($settings["bsht_tbk_usr"]);
			$message = str_replace('#昵称#', $mc_infos['nickname'], $message);
			$message = str_replace('#积分#', $mc_infos['credit1'], $message);
			$message = str_replace('#余额#', $mc_infos['credit2'], $message);
			$message = str_replace('#总粉丝数#', $fansallnum, $message);
			$message = str_replace('#性别#', $fansusr['gender'], $message);
			$message = str_replace('#国家#', $mc_infos['country'], $message);
			$message = str_replace('#省#', $mc_infos['province'], $message);
			$message = str_replace('#市#', $mc_infos['city'], $message);
			$message = str_replace('#公众号名称#', $account_name, $message);
			$message = str_replace('#自定义URL-1#', $bsht_tbk_diyurl1, $message);
			$message = str_replace('#自定义URL-2#', $bsht_tbk_diyurl2, $message);
			$message = str_replace('#自定义URL-3#', $bsht_tbk_diyurl3, $message);
			$account = WeAccount::create();
			$custom = array('msgtype' => 'text', 'text' => array('content' => urlencode($message)), 'touser' => $this->message['from'],);
			$account->sendCustomNotice($custom);
		}
		if ($this->message['msgtype'] == 'event') {
			if ($this->message['event'] == 'unsubscribe') {
				$mc_infos = mc_fetch($this->message['from']);
				$reply = pdo_fetch('select * from ' . tablename('bsht_tbk_poster') . ' where uniacid=:uniacid order by id asc limit 1', array(':uniacid' => $mc_infos['uniacid']));
				if ($reply['rscore'] == 0) {
					return '';
				}
				$cscore3 = $reply['cscore'];
				$pscore3 = $reply['pscore'];
				$m_fans = pdo_fetch('select * from ' . tablename('bsht_tbk_user') . ' where uniacid=:uniacid AND from_user=:from_user order by id asc limit 1', array(':uniacid' => $mc_infos['uniacid'], ':from_user' => $this->message['from']));
				if ($m_fans['helpid'] && empty($m_fans['hasdel'])) {
					$s_fans = pdo_fetch('select * from ' . tablename('bsht_tbk_user') . ' where uniacid=:uniacid AND uid=:uid order by id asc limit 1', array(':uniacid' => $mc_infos['uniacid'], ':uid' => $m_fans['helpid']));
					if ($cscore3 > 0) {
						if ($cscore3) {
							mc_credit_update($s_fans['uid'], 'credit1', -$cscore3, array($s_fans['uid'], '1级取消关注'));
						}
						$rtips = str_replace('#昵称#', $mc_infos['nickname'], $reply['rtips']);
						$rtips = str_replace('#积分#', $cscore3, $rtips);
						$this->sendText($s_fans['from_user'], $rtips);
						if ($pscore3 > 0) {
							if ($s_fans['helpid']) {
								$p_fans = pdo_fetch('select * from ' . tablename('bsht_tbk_user') . ' where uniacid=:uniacid AND uid=:uid order by id asc limit 1', array(':uniacid' => $mc_infos['uniacid'], ':uid' => $s_fans['helpid']));
								if ($pscore3) {
									mc_credit_update($p_fans['uid'], 'credit1', -$pscore3, array($s_fans['uid'], '2级取消关注'));
								}
								$rtips3 = str_replace('#昵称#', $mc_infos['nickname'], $reply['rtips']);
								$rtips3 = str_replace('#积分#', $pscore3, $rtips3);
								$this->sendText($p_fans['from_user'], $rtips3);
							}
						}
					}
				}
				pdo_update('bsht_tbk_user', array('follow' => 0, 'hasdel' => 1), array('uid' => $mc_infos['uid'], 'uniacid' => $mc_infos['uniacid']));
			}
		}
	}
}